package com.zgm.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Created by 张公铭 on 2017/7/13 0013.
 * SharedPrefernces 工具类
 */

public class SharedPreferencesUtis
{
    //保存对象
    public static boolean saveSharedPreference(Context context, String fileName, String key, Object object)
    {
        // TODO Auto-generated method stub
        SharedPreferences share = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        if (object == null)
        {
            SharedPreferences.Editor editor = share.edit().remove(key);
            return editor.commit();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try
        {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
        } catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        // 将对象放到OutputStream中
        // 将对象转换成byte数组，并将其进行base64编码
        String objectStr = new String(android.util.Base64.encode(baos.toByteArray(), android.util.Base64.DEFAULT));
        try
        {
            baos.close();
            oos.close();
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor editor = share.edit();
        // 将编码后的字符串写到base64.xml文件中
        editor.putString(key, objectStr);
        return editor.commit();
    }

    /**
     * 读取
     *
     * @param context
     * @param fileName
     * @param key
     * @return
     */
    public static Object getObjectFromShare(Context context, String fileName, String key)
    {
        SharedPreferences sharePre = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        try
        {
            String wordBase64 = sharePre.getString(key, "");
            // 将base64格式字符串还原成byte数组
            if (wordBase64 == null || wordBase64.equals(""))
            { // 不可少，否则在下面会报java.io.StreamCorruptedException
                return null;
            }
            byte[] objBytes = android.util.Base64.decode(wordBase64.getBytes(),
                    android.util.Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            // 将byte数组转换成product对象
            Object obj = ois.readObject();
            bais.close();
            ois.close();
            return obj;
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
